package com.yaowk.weixin.controller;

import com.jfinal.aop.Before;
import com.jfinal.kit.Kv;
import com.jfinal.plugin.activerecord.Page;
import com.xiaoleilu.hutool.util.ObjectUtil;
import com.yaowk.common.constant.ServiceCode;
import com.yaowk.common.controller.BaseController;
import com.yaowk.common.model.base.Time;
import com.yaowk.device.model.Device;
import com.yaowk.device.model.Goods;
import com.yaowk.system.validator.PlatformIdValidator;
import com.yaowk.weixin.model.Fans;
import com.yaowk.weixin.model.Order;
import org.apache.shiro.authz.annotation.RequiresAuthentication;
import org.apache.shiro.authz.annotation.RequiresPermissions;

/**
 * @authc yaowk
 * 2017/7/25
 */
@RequiresAuthentication
@RequiresPermissions("weixin:order")
@Before(PlatformIdValidator.class)
public class OrderController extends BaseController {

    public void list() {
        Integer deviceId = getParaToInt("deviceId");
        Integer goodsId = getParaToInt("goodsId");
        Integer platformId = getParaToInt("platformId");

        Time time = getBean(Time.class, "", true);

        Kv kv = Kv.by("platform_id = ", platformId);
        if (ObjectUtil.isNotNull(deviceId)) {
            kv.set("device_id = ", deviceId);
        }
        if (ObjectUtil.isNotNull(goodsId)) {
            kv.set("goods_id = ", goodsId);
        }
        if (ObjectUtil.isNotNull(time.getBeginTime())) {
            kv.set("create_time > ", time.getBeginTime());
        }
        if (ObjectUtil.isNotNull(time.getEndTime())) {
            kv.set("create_time < ", time.getEndTime());
        }
        Page<Order> page = Order.dao.paginate(getPage(), kv);
        renderJson(page);
    }

    public void index() {
        Integer id = getParaToInt();
        Integer platformId = getParaToInt("platformId");
        Order order = Order.dao.findFirst(Kv.by("id = ", id).set("platform_id = ", platformId));
        if (ObjectUtil.isNotNull(order)) {
            Kv result = Kv.create();
            result.set("order", order);
            result.set("device", Device.dao.findById(order.getDeviceId()));
            result.set("goods", Goods.dao.findById(order.getGoodsId()));
            result.set("fans", Fans.dao.findById(order.getFansId()));
            renderJson(result);
            return;
        }
        renderFail(ServiceCode.ERROR, null);
    }
}
